import { returnArrObjKeyVal } from '_commonFn/array'

// 用于获取URL相关

/**
 * 检查URL是否有相关相关字段
 * @param queryStr: URL 参数对象
 * @param param: URL 参数对象的KEY
 */
function checkIsHadParam({queryStr = '', param = ''}){
    if(queryStr){
        if(queryStr[param]) return true
        return false
    }
    return false
}

/**
 * 替换URL指定字段的值
 * @param queryStr: URL 参数对象
 * @param param: URL 参数对象的KEY
 */
function replaceUrlParamVal({queryStr = '', param = '', val = '', link = ''}){
    if(queryStr[param]){
        const newQueryStr = Object.assign({}, queryStr)
        newQueryStr[param] = val
        return newQueryStr
    }
    if(link && param){
        link = link.replace(param, val)
    }
    return queryStr || link
}

// 获取url中"?"符后的字串
export function getQueryStr() {
    var qs = location.search.substr(1), // 获取url中"?"符后的字串  
        args = {}, // 保存参数数据的对象
        items = qs.length ? qs.split("&") : [], // 取得每一个参数项,
        item = null,
        len = items.length;

    for (var i = 0; i < len; i++) {
        item = items[i].split("=");
        var name = decodeURIComponent(item[0]),
            value = decodeURIComponent(item[1]);
        if (name) {
            args[name] = value;
        }
    }
    return args;
}

// 获取Url参数
// paramArrIndex：Url第index个参数
// keyArr 数组，数组内包含对象
// query url参数
export const getQueryStrParams = ({params = [], query = {}}) => {
    if (params.length > 0) {
        const queryStr = Object.keys(query).length > 0 && query || getQueryStr()
        if(queryStr.parms){
            const parmsArray = queryStr.parms.split('-');
            parmsArray.forEach((item, index) => {
                if (item && params[index]) {
                    if (typeof params[index] === 'object') {
                        const val = returnArrObjKeyVal({
                            arr: params[index].keyArr,
                            key: parmsArray[params[index].paramArrIndex]
                        })
                        if (val) {
                            queryStr[params[index]] = val
                        } else {
                            queryStr[params[index]] = item
                        }
                    }
                    queryStr[params[index]] = item
                }
            })
        }
        return queryStr
    }
    return {}
}

//如果小于等于一个参数，则返回原url。
//否则获取Url的所有参数值，并将参数用-分割，以参数名parms加参数值返回
function returnUrlToLinea(url = location.href.split('#')[0]) {
    console.log('url', url)
    const urlParms = url.split('?')[1] ? url.split('?')[1].split('&') : ''
    let state = sessionStorage.getItem('USER_SHARE_URL_INFO') || ''
    // console.log('urlParms', urlParms)
    if (urlParms && typeof urlParms === 'object' && urlParms.length > 1) {
        let parmsStr = ''
        const urlNoPrams = url.split('?')[0] 
        for (let i = 0, len = urlParms.length; i < len; i++) {
            if (urlParms[i].split('=')[0] === 'shareUser') {
                if (state) {
                    continue
                } else {
                    state = `&state=${urlParms[i].split('=')[1]}`
                }
            } else {
                parmsStr += urlParms[i].split('=')[1] + '-'
            }
        }
        parmsStr = parmsStr.substr(0, parmsStr.length - 1) + `${state ? '&state=' + state : state}` //去掉最后一个字符串"-"
        return urlNoPrams + '?parms=' + parmsStr
    } else {
        if (urlParms.length == 1) {
            return url + `${state ? '&state=' + state : state}`
        } else {
            return url + `${state ? '?state=' + state : state}`
        }
    }
}

// 将一个对象拼接成字符串
export const objToStr = (obj) => {
    let str = ''
    if (typeof obj === 'object') {
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (str) {
                    str += `&${key}=${obj[key]}`
                } else {
                    str = `?${key}=${obj[key]}`
                }
            }
        }
    }
    return str
}

export { checkIsHadParam, replaceUrlParamVal, returnUrlToLinea }